﻿using System;
using System.Text;
using System.IO;
//using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Xml;

namespace Serializer
{
    public static class Serializer
{
    /// <summary>
    /// Serialize and object
    /// </summary>
    /// <param name="o">
    /// <param name="file_name">
    public static void Write<T>(T o, string file_name)
    {
        try
        {
            FileStream stream = File.Open(file_name, FileMode.OpenOrCreate);
            DataContractSerializer dcs = new DataContractSerializer(typeof(T), null, int.MaxValue, false, true, null);
            using (XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
            {
                dcs.WriteObject(xdw, o);
            }
            stream.Close();
        }
        catch (Exception e)
        {
            throw e;
        }
    }
 
    /// <summary>
    /// Load an object from an XML source
    /// </summary>
    /// <param name="file_name">
    /// <returns></returns>
    public static T Read<T>(string file_name)
    {
        try
        {
            FileStream stream = File.OpenRead(file_name); DataContractSerializer dcs = new DataContractSerializer(typeof(T), null, int.MaxValue, false, true, null);
            using (XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(stream, Encoding.UTF8, new XmlDictionaryReaderQuotas() { MaxDepth = int.MaxValue }, null))
            {
                return (T)dcs.ReadObject(xdr);
            }
        }
        catch (Exception e)
        {
            throw e;
        }
    }
}
}
